package com.dp.service.impl3;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.EbookVo;
import com.dp.pojo.JsonPage;
import com.dp.pojo.News;

import com.dp.pub.SysProperty;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.util.ImageScalee;
import com.dp.util.InterUtil;
import com.dp.util.KeyGenerator;
import com.dp.vo.ChannelEbookPK;
import com.dp.vo.NewsContenttitle;
import com.dp.vo.NewsExtendsChannelTitle;
import com.dp.vo.NewsExtendsChannelTitlePK;
import com.dp.vo.NewsResources;
import com.dp.vo.TChannelEbook;
import com.dp.vo.TChannels;
import com.dp.vo.TEbookContent;
import com.dp.vo.TEbookResource;
import com.dp.vo.TEbookSection;
import com.dp.vo.TGenre;
import com.dp.vo.TResourcedelete;
import com.dp.vo.TServiceInfo;

@Service
@Transactional
public class EbookServiceImpl3 extends BaseImpl {

	/**
	 * 得到电子书内容列表
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<EbookVo> findAllEbook(DataMap hashMap, Integer firstrow,
			Integer maxrow) {
		TEbookContent ebookContent = (TEbookContent) hashMap
				.get("ebookContent");
		String userids=(String)hashMap.get("userids");
		JsonPage jpage=(JsonPage)hashMap.get("jpage");
		String newstype = null;
		if (hashMap.get("newstype") != null) {
			newstype = hashMap.get("newstype").toString();
		}
		StringBuffer sf = new StringBuffer("SELECT t FROM TEbookContent t ");

		Object role_id = hashMap.get("role_id");
		Object user_id = hashMap.get("user_id");

		String channelid = "";
		// 按栏目查询
		if (hashMap.get("channelid") != null) {
			channelid = hashMap.get("channelid").toString();
			sf
					.append(" ,NewsContenttitle nc,NewsExtendsChannelTitle nect,NewsExtendsChannel nec ");
			sf
					.append(" WHERE nc.cid=nect.newsContenttitle.cid  and t.contentid=nc.contentid and nect.newsExtendsChannelTitlePK.channleid=nec.channleid  and nec.channelId.channelId='"
							+ channelid + "'");
		}else{
			sf.append(" WHERE 1=1");
		}

		if (StringIsNotNull(role_id) && StringIsNotNull(user_id)) {
			sf.append(" AND userid='" + user_id + "'");
		}else if(userids!=null){
			sf.append(" AND userid in ("+ userids + ")");
		}
		if (ebookContent != null) {
			if (ebookContent.getBookname() != null
					&& ebookContent.getBookname().toString().trim().length() > 0) {
				sf.append(" AND t.bookname like '%"
						+ ebookContent.getBookname() + "%'");
			}
			if (newstype != null && newstype.trim().length() > 0) {
				sf
						.append(" AND t.newsContenttitle.newstype='" + newstype
								+ "'");
			}
			if (ebookContent.getStatus() != null
					&& ebookContent.getStatus().toString().trim().length() > 0) {
				sf.append(" AND t.status='" + ebookContent.getStatus() + "'");
			}

		}
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sf.append(" order by t."+jpage.getSidx()+" "+jpage.getSord()+"");
			}
		}
		List<TEbookContent> queryList = new ArrayList<TEbookContent>();
		List<EbookVo> result=new ArrayList<EbookVo>();
		try {
			
			Query query = em.createQuery(sf.toString());
			if (firstrow != null) {
				query.setFirstResult(firstrow);
			}
			if (maxrow != null) {
				query.setMaxResults(maxrow);
			}
			queryList = query.getResultList();
			if(queryList.size()>0){
				result=new ArrayList<EbookVo>(queryList.size());
				EbookVo ebook_temp=null;
				for(TEbookContent content_temp:queryList){
					ebook_temp=new EbookVo();
					ebook_temp.setContentid(content_temp.getContentid());
					ebook_temp.setBookname(content_temp.getBookname());
					if(content_temp.getServiceInfo()!=null){
						ebook_temp.setService_code(content_temp.getServiceInfo().getServiceCode());
						ebook_temp.setServicename(content_temp.getServiceInfo().getServicename());
						ebook_temp.setPrice(content_temp.getServiceInfo().getPrice());
					}
					ebook_temp.setBookintro(content_temp.getBookintro());
					ebook_temp.setBooktag(content_temp.getBooktag());
					if(content_temp.getGenre()!=null){
						ebook_temp.setGenre_id(content_temp.getGenre().getGenreId());
						ebook_temp.setGenre_name(content_temp.getGenre().getGenreName());
					}
					ebook_temp.setAuthor(content_temp.getAuthor());
					ebook_temp.setLanguage(content_temp.getLanguage());
					ebook_temp.setPublisher(content_temp.getPublisher());
					ebook_temp.setCopyright(content_temp.getCopyright());
					ebook_temp.setPublishtime(content_temp.getPublishtime());
					ebook_temp.setUserid(content_temp.getUserid());
					ebook_temp.setAddtime(content_temp.getAddtime());
					ebook_temp.setLastupdatetime(content_temp.getLastupdatetime());
					ebook_temp.setStatus(content_temp.getStatus());
					ebook_temp.setSeiralstatus(content_temp.getSeiralstatus());
					ebook_temp.setAudituser(content_temp.getAudituser());
					ebook_temp.setCause(content_temp.getCause());
					ebook_temp.setMarkcode(content_temp.getMarkcode());
					ebook_temp.setCharcount(content_temp.getCharcount());
					ebook_temp.setNewstype(content_temp.getNewsContenttitle().getNewstype());
					result.add(ebook_temp);
				}
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获得栏目列表
	 * 
	 * @param hashMap
	 * @return List<TChannels>
	 */
	public List<TChannels> getChannelList(DataMap hashMap) {
		
		String jpql = "SELECT ch FROM TChannels ch WHERE ch.status='"
				+ BookConfig.channel_status_enable + "' AND (ch.channelType='"
				+ BookConfig.channel_type_ebook + "' or ch.channelType='"+BookConfig.channel_type_magazine+"') AND (functionName='"
				+ BookConfig.channel_song + "' OR functionName='"
				+ BookConfig.channel_last + "')";
		Object employee_id = hashMap.get("employee_id");
		Object role_id = hashMap.get("role_id");

		if (role_id != null) {
			if (!role_id.equals("") && StringIsNotNull(employee_id)) {
				jpql = "select ch from TChannels ch,TUserChannels uc WHERE ch.channelId=uc.channelId AND ch.status='"
						+ BookConfig.channel_status_enable
						+ "' AND (ch.channelType='"
						+ BookConfig.channel_type_ebook
						+ "' or ch.channelType='"+BookConfig.channel_type_magazine+"') AND (ch.functionName='"
						+ BookConfig.channel_last
						+ "' OR ch.functionName='"
						+ BookConfig.channel_song
						+ "') AND uc.employeeId='" + employee_id + "'";
			}
		}
		List<TChannels> queryList=new ArrayList<TChannels>();
		try {
			Query query = em.createQuery(jpql);
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error(" getChannelList fail !!!"+e.getMessage());
		}
		return queryList;
	}

	
	/**
	 * 根据id得到TEbookContent
	 * 
	 * @param contentid
	 * @return
	 */
	public TEbookContent getTEbookContentByContentid(String contentid) {
		
		StringBuffer sf = new StringBuffer(
				"SELECT t FROM TEbookContent t WHERE 1=1");
		sf.append(" AND t.contentid='" + contentid + "'");
		Object obj = null;
		Query query = null;
		try {
			query = em.createQuery(sf.toString());
			obj = query.getSingleResult();
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		
		if (obj == null) {
			return null;
		} else {
			return (TEbookContent) obj;
		}
	}

	/**
	 * 根据id得到TEbookSection
	 * 
	 * @param contentid
	 * @return
	 */
	public TEbookSection getTEbookSectionByContentid(String section_id) {
		
		StringBuffer sf = new StringBuffer(
				"SELECT t FROM TEbookSection t WHERE 1=1");
		sf.append(" AND t.sectionid='" + section_id + "'");
		
		Object obj = null;
		Query query = null;
		try {
			query = em.createQuery(sf.toString());
			obj = query.getSingleResult();
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		if (obj == null) {
			return null;
		} else {
			return (TEbookSection) obj;
		}
	}

	/**
	 * 业务列表
	 * 
	 * @param hashMap
	 * @return
	 */
	public List<TServiceInfo> getAllServiceInfo(DataMap hashMap) {
		List<TServiceInfo> serviceList = new ArrayList<TServiceInfo>();
		String sql = "select p.serviceid,p.servicename,p.service_code,p.price,p.price_type,p.servicetype,p.access_no,p.port_type,p.content,p.content_type,p.processClass,p.carrier,p.spnumber,p.order_success_msg,p.ctrmand_cmd,p.ctrmand_no,p.starttime" +
				" from t_service_info p,t_user_prices up where p.service_code=up.service_code ";
		Object employee_id = hashMap.get("employee_id");
		Object role_id = hashMap.get("role_id");
		if (role_id != null) {
			if (!role_id.equals("") && StringIsNotNull(employee_id)) {
				sql = sql + " AND employee_id='" + employee_id + "'";
			}
		} else if (role_id == null || role_id.equals("")) {
			sql = "select p.serviceid,p.servicename,p.service_code,p.price,p.price_type,p.servicetype,p.access_no,p.port_type,p.content,p.content_type,p.processClass,p.carrier,p.spnumber,p.order_success_msg,p.ctrmand_cmd,p.ctrmand_no,p.starttime" +
					" from t_service_info p ";
		}
		List list = new ArrayList();

		try {
			list = queryALLResultSet(sql);
		} catch (Exception e) {
			logger.info(" getPriceAll fail !!!" + e.getMessage());
			return null;
		}
		for (int i = 0; i < list.size(); i++) {
			DataMap hash = new DataMap();
			hash = (DataMap) list.get(i);
			TServiceInfo tserviceInfo = new TServiceInfo();
			tserviceInfo.setServiceid(Long.parseLong(hash.get("serviceid")
					.toString()));
			tserviceInfo.setServiceCode(hash.get("service_code").toString());
			tserviceInfo.setServicename(hash.get("servicename").toString());
			tserviceInfo.setPrice(new BigInteger(hash.get("price").toString()));
			serviceList.add(tserviceInfo);
		}
		return serviceList;
	}

	/**
	 * 增加电子书内容信息
	 * 
	 * @param TEbookContent
	 *            电子书内容
	 * @param channelid
	 *            电子书内容关联栏目
	 * @return
	 */
	public TEbookContent addEbookContent(DataMap hashMap, String channelid) {
		boolean b = false;
		TEbookContent ebookContent = (TEbookContent) hashMap
				.get("ebookContent");
			
			// 增加电子书内容
			String content_id = com.dp.util.BaseBean
					.ObjectToString(KeyGenerator.getInstance().getNextKeyValue(
							"t_auditcontents"));
			ebookContent.setContentid(content_id);
			// insert news_contenttitle
			NewsContenttitle newsContenttitle = new NewsContenttitle();
			newsContenttitle.setContentid(ebookContent.getContentid());
			newsContenttitle.setContenttitle(ebookContent.getBookname());
			String contenticon = SysProperty.getPrep("sysiconid_title");
			if (contenticon == null || contenticon.equals(""))
				contenticon = "1";
			newsContenttitle.setContenticon(Integer.parseInt(contenticon));
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String nowtime = fmt.format(new Date());
			String contenttext = "" 
					/*+ InterUtil.rb_jsp.getString("game.name")
					+ ":" + ebookContent.getBookname() + "@"
					+ InterUtil.rb_jsp.getString("ebook.is.end") + ":"
					+ ebookContent.getSeiralstatus() + "@"
					+ InterUtil.rb.getString("src.language") + ":"
					+ ebookContent.getLanguage() + "@"
					+ InterUtil.rb.getString("src.updatetime") + ":" + nowtime
					+ "@" + InterUtil.rb_jsp.getString("ebook.publishing.house") + ":"
					+ ebookContent.getPublisher() + "@"
					+ InterUtil.rb.getString("src.intro") + ":"*/
					+ ebookContent.getBookintro() + "";
			newsContenttitle.setContenttext(contenttext);
			// String newstype = InterUtil.rb.getString("src.theme");
			String newstype = null;
			if (hashMap.get("newstype") != null) {
				newstype = hashMap.get("newstype").toString();
			}
			if("magazine".equals(newstype)){
				newsContenttitle.setContenttext(ebookContent.getBookintro());
			}
			newsContenttitle.setNewstype(newstype);

			em.persist(newsContenttitle);
			em.persist(ebookContent);
			// if(channelid!=null&&!"".equals(channelid)){
			// 主题内容关联栏目
			for (String chid : channelid.split(",")) {
				// 频道栏目关联中间表 取自增长channleid
				String jpql = "select channleid from NewsExtendsChannel where channelId='"
						+ chid + "'";
				Query query = em.createQuery(jpql);
				Integer channleid = Integer.parseInt(query.getSingleResult()
						.toString());
				jpql = "select cid from NewsContenttitle where contentid='"
						+ ebookContent.getContentid() + "'";
				query = em.createQuery(jpql);
				Integer cid = Integer.parseInt(query.getSingleResult()
						.toString());

				NewsExtendsChannelTitle newsExtendsChannelTitle = new NewsExtendsChannelTitle();
				newsExtendsChannelTitle
						.setNewsExtendsChannelTitlePK(new NewsExtendsChannelTitlePK(
								channleid, cid));
				newsExtendsChannelTitle.setContentstatus(0);
				newsExtendsChannelTitle.setIstest(1);
				newsExtendsChannelTitle.setIsnew(1);
				em.persist(newsExtendsChannelTitle);

				// 栏目-电子书内容关联中间表
				TChannelEbook channelEbook = new TChannelEbook();
				channelEbook.setChannelEbookPK(new ChannelEbookPK(cid,
						channleid));
				em.persist(channelEbook);
			}
			return ebookContent;
	}

	/**
	 * 修改电子书内容信息
	 * 
	 * @param hashMap
	 * @param channelid
	 * @return
	 */
	public TEbookContent updateEbookContent(DataMap hashMap, String channelid) {
		boolean b = false;
		TEbookContent ebookContent = (TEbookContent) hashMap
				.get("ebookContent");
		String newstype = "";
		if (hashMap.get("newstype") != null
				&& !"".equals(hashMap.get("newstype"))) {
			newstype = hashMap.get("newstype").toString();
		}
			
			// 修改主题内容

			em.merge(ebookContent);
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String nowtime1 = new Date().toString();
			String nowtime = fmt.format(new Date());
			String contenttext = ""
				/* + InterUtil.rb_jsp.getString("game.name")
					+ ":" + ebookContent.getBookname() + "@"
					+ InterUtil.rb_jsp.getString("ebook.is.end") + ":"
					+ ebookContent.getSeiralstatus() + "@"
					+ InterUtil.rb.getString("src.language") + ":"
					+ ebookContent.getLanguage() + "@"
					+ InterUtil.rb.getString("src.updatetime") + ":" 
					+ nowtime + "@"
					+ InterUtil.rb_jsp.getString("ebook.publishing.house") + ":"
					+ ebookContent.getPublisher() + "@"
					+ InterUtil.rb.getString("src.intro") + ":"*/
					+ ebookContent.getBookintro() + "";
			if("magazine".equals(newstype)){
				ebookContent.setBookintro(contenttext);
			}
			// 更新newsContenttitle表记录
			String jpql = "UPDATE NewsContenttitle SET contenttitle='"
					+ ebookContent.getBookname() + "',contenttext='"
					+ ebookContent.getBookintro() + "',newstype='" + newstype
					+ "',updatetime='"+nowtime+"' WHERE contentid='" + ebookContent.getContentid() + "'";
			Query query = em.createQuery(jpql);
			query.executeUpdate();

			// 更新电子书内容 栏目-内容(NewsContenttitle) 栏目-电子书内容关系(TChannelEbook)
			jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
					+ ebookContent.getContentid() + "'";
			query = em.createQuery(jpql);
			Integer cid = Integer.parseInt(query.getSingleResult().toString());
			// 删除电子书内容 原 栏目-内容
			jpql = "DELETE FROM NewsExtendsChannelTitle WHERE newsExtendsChannelTitlePK.cid="
					+ cid + "";
			query = em.createQuery(jpql);
			query.executeUpdate();
			// 删除电子书内容 原 栏目-电子书内容关系
			jpql = "DELETE FROM TChannelEbook WHERE channelEbookPK.contentid="
					+ cid + "";
			query = em.createQuery(jpql);
			query.executeUpdate();

			// if(channelid!=null&&!"".equals(channelid)){
			// 增加电子书内容 栏目-内容
			for (String chid : channelid.split(",")) {
				// 频道栏目关联中间表 取自增长channleid
				jpql = "select channleid from NewsExtendsChannel where channelId='"
						+ chid + "'";
				query = em.createQuery(jpql);
				Integer channleid = Integer.parseInt(query.getSingleResult()
						.toString());

				NewsExtendsChannelTitle newsExtendsChannelTitle = new NewsExtendsChannelTitle();
				newsExtendsChannelTitle
						.setNewsExtendsChannelTitlePK(new NewsExtendsChannelTitlePK(
								channleid, cid));
				newsExtendsChannelTitle.setContentstatus(0);
				newsExtendsChannelTitle.setIstest(1);
				newsExtendsChannelTitle.setIsnew(1);
				em.persist(newsExtendsChannelTitle);

				// 栏目-电子书内容关联中间表
				TChannelEbook channelEbook = new TChannelEbook();
				channelEbook.setChannelEbookPK(new ChannelEbookPK(cid,
						channleid));
				em.persist(channelEbook);
			}
			return ebookContent;
	}

	/**
	 * 获得已选栏目列表
	 * 
	 * @param channelid
	 * @return
	 */
	public List<TChannels> getSelectedChannelListbyCid(String contentid) {
		
		String jpql = "SELECT t FROM TChannels t WHERE channelId in (SELECT newsExtendsChannel.channelId"
				+ " FROM NewsExtendsChannelTitle n WHERE 1=1 and newsContenttitle.contentid='"
				+ contentid + "')";
		Query query = em.createQuery(jpql);
		List<TChannels> queryList = query.getResultList();
		return queryList;
	}

	/**
	 * 获得电子书内容下章节列表
	 * 
	 * @param contentid
	 * @return
	 */
	public List<EbookVo> getTEbookSectionListByContent(DataMap hashMap,
			Integer firstrow, Integer maxrow) {
		TEbookContent ebookContent = null;
		if (hashMap.get("ebookContent") != null) {
			ebookContent = (TEbookContent) hashMap.get("ebookContent");
		}
		TEbookSection ebookSection = (TEbookSection) hashMap
				.get("ebookSection");
		JsonPage jpage=(JsonPage)hashMap.get("jpage");
		StringBuffer sf = new StringBuffer(
				"SELECT t FROM TEbookSection t,TEbookContent tec WHERE 1=1 AND t.tebookContent.contentid=tec.contentid ");

		Object role_id = hashMap.get("role_id");
		Object user_id = hashMap.get("user_id");
		if (role_id != null) {
			if (!role_id.equals("") && StringIsNotNull(user_id)) {
				sf.append(" AND t.tebookContent.userid='" + user_id + "' ");
			}
		}
		if (ebookContent != null) {
			if (ebookContent.getContentid() != null
					&& ebookContent.getContentid().toString().trim().length() > 0) {
				sf.append(" AND t.tebookContent.contentid='"
						+ ebookContent.getContentid() + "'");
			}
			if (ebookContent.getBookname() != null
					&& ebookContent.getBookname().toString().trim().length() > 0) {
				sf.append(" AND t.tebookContent.bookname like '%"
						+ ebookContent.getBookname() + "%'");
			}

		}
		if (ebookSection != null) {
			if (ebookSection.getSectionname() != null
					&& ebookSection.getSectionname().toString().trim().length() > 0) {
				sf.append(" AND t.sectionname like '%"
						+ ebookSection.getSectionname() + "%'");
			}
			if (ebookSection.getSectionstatus() != null
					&& ebookSection.getSectionstatus().toString().trim()
							.length() > 0) {
				sf.append(" AND t.sectionstatus='"
						+ ebookSection.getSectionstatus()
						+ "' AND tec.status='pass'");
			}
			if (ebookSection.getIsfree() != null
					&& ebookSection.getIsfree().toString().trim().length() > 0) {
				sf.append(" AND t.isfree='" + ebookSection.getIsfree() + "'");
			}
			if (ebookSection.getIslink() != null
					&& ebookSection.getIslink().toString().trim().length() > 0) {
				sf.append(" AND t.islink='" + ebookSection.getIslink() + "'");
			}
			if (ebookSection.getCause() != null
					&& ebookSection.getCause().toString().trim().length() > 0) {
				sf.append(" AND t.cause='" + ebookSection.getCause() + "'");
			}
		}
		if(hashMap.get("begin_time") != null && !"".equals(hashMap.get("begin_time"))) {
			hashMap.put("begin_time", hashMap.get("begin_time")+" 0:00:00");
			sf.append(" AND t.updatetime > '" + hashMap.get("begin_time") + "'");
		}
		if(hashMap.get("end_time") != null && !"".equals(hashMap.get("end_time"))) {
			hashMap.put("end_time", hashMap.get("end_time")+" 23:59:59");
			sf.append(" AND t.updatetime < '" + hashMap.get("end_time") + "'");
		}
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sf.append(" order by t."+jpage.getSidx()+" "+jpage.getSord()+"");
			}
		}
		
		List<TEbookSection> queryList = null;
		List<EbookVo> result=new ArrayList<EbookVo>();
		try {
			Query query = em.createQuery(sf.toString());
			if (firstrow != null) {
				query.setFirstResult(firstrow);
			}
			if (maxrow != null) {
				query.setMaxResults(maxrow);
			}
			queryList = query.getResultList();
			
			if(queryList.size()>0){
				result=new ArrayList<EbookVo>(queryList.size());
				EbookVo ebook_temp=null;
				for(TEbookSection content_temp:queryList){
					ebook_temp=new EbookVo();
					ebook_temp.setContentid(content_temp.getTebookContent().getContentid());
					ebook_temp.setSectionid(content_temp.getSectionid());
					ebook_temp.setSectionname(content_temp.getSectionname());
					ebook_temp.setSectionorder(content_temp.getSectionorder());
					ebook_temp.setIsfree(content_temp.getIsfree());
					ebook_temp.setIslink(content_temp.getIslink());
					ebook_temp.setSectionstatus(content_temp.getSectionstatus());
					ebook_temp.setUpdatetime(content_temp.getUpdatetime());
					ebook_temp.setCause(content_temp.getCause());
					ebook_temp.setAdduser(content_temp.getAdduser());
					ebook_temp.setNewstype(content_temp.getTebookContent().getNewsContenttitle().getNewstype());
					ebook_temp.setBookname(content_temp.getTebookContent().getBookname());	//审核章节
					ebook_temp.setFilepath(content_temp.getFilepath());
					result.add(ebook_temp);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		} 
		return result;
	}

	/**
	 * 新增章节信息
	 * 
	 * @param dataMap
	 * @return
	 */
	public TEbookSection addEbookSection(DataMap hashMap) {
		boolean b = false;
		TEbookSection ebookSection = (TEbookSection) hashMap
				.get("ebookSection");
		TEbookContent ebookContent = (TEbookContent) hashMap
				.get("ebookContent");
		String magazine =(String) hashMap.get("magazine");//杂志内容章节
		
			String jpql = "SELECT max(sectionid) FROM TEbookSection";
			Query query = em.createQuery(jpql);
			Integer max_sectionid = 0;
			if (query.getSingleResult() != null) {
				max_sectionid = Integer.parseInt(query.getSingleResult()
						.toString());
			}
			jpql = "SELECT max(sectionorder) FROM TEbookSection WHERE tebookContent.contentid='"
					+ ebookContent.getContentid() + "'";
			if(magazine!=null){
				jpql+=" and isfree="+ebookSection.getIsfree()+"";
			}
			query = em.createQuery(jpql);
			Integer max_sectionorder = 0;
			if (query.getSingleResult() != null) {
				max_sectionorder = Integer.parseInt(query.getSingleResult()
						.toString());
			}
			ebookSection.setSectionid((max_sectionid + 1));
			if("".equals(ebookSection.getSectionorder())||ebookSection.getSectionorder()==null){
				ebookSection.setSectionorder((max_sectionorder + 1));
			}
			em.persist(ebookSection);

			ebookContent.setLastupdatetime(new Date());
			ebookContent = em.merge(ebookContent);
			
			return ebookSection;

	}
	
	
	/**
	 * 获得电子书下章节最大排序值+1
	 * 章节内容生产html文件。以此命名
	 * @param dataMap
	 * @return
	 */
	public Integer getSectionorder(DataMap hashMap) {
		TEbookContent ebookContent = (TEbookContent) hashMap.get("ebookContent");
		boolean b = false;
		Integer max_sectionorder = 0;
		try {
			
			String jpql = "SELECT max(sectionorder) FROM TEbookSection WHERE tebookContent.contentid='"
					+ ebookContent.getContentid() + "'";
			Query query = em.createQuery(jpql);
			
			if (query.getSingleResult() != null) {
				max_sectionorder = Integer.parseInt(query.getSingleResult()
						.toString());
			}

			b = true;
		} catch (Exception e) {
			b = false;
			logger.error(e.getMessage());
		} 
		if (b) {
			return max_sectionorder+1;
		} else {
			return null;
		}

	}
	
	
	/**
	 * 修改章节信息
	 * 
	 * @param dataMap
	 * @return
	 */
	public TEbookSection updateEbookSection(DataMap hashMap) {
		boolean b = false;
		TEbookSection ebookSection = (TEbookSection) hashMap
				.get("ebookSection");
		String deleteResUrls = null;
		if (hashMap.get("deleteResUrls") != null) {
			deleteResUrls = hashMap.get("deleteResUrls").toString();
		}
			
			ebookSection = em.merge(ebookSection);
			TEbookContent ebookContent = ebookSection.getTebookContent();
			ebookContent.setLastupdatetime(new Date());
			em.merge(ebookContent);
			if (deleteResUrls != null && !"".equals(deleteResUrls)) {
				// 章节中有删除的附件
				for (String resource_id : deleteResUrls.split(",")) {
					System.out.println("resource_id:" + resource_id);
					TEbookResource ebookResource = em.find(
							TEbookResource.class, resource_id);
					// 删除的记录插入t_resourcedelete
					TResourcedelete resourcedelete = new TResourcedelete();
					resourcedelete.setSpcode(ebookResource.getSpcode());
					resourcedelete.setFormat(ebookResource.getCformat());
					resourcedelete.setType(ebookResource.getCtype());
					resourcedelete.setUrl(ebookResource.getCurl());
					// 备用字段 not 备注
					// resourcedelete.setComments("ebook@resourceid:"+ebookResource.getResourceid()+",contentid:"+ebookResource.getTebookContent().getContentid()+",sectionid:"+ebookResource.getTebookSection().getSectionid()+"");
					em.persist(resourcedelete);
					if (ebookResource.getNewsrid() != null) {
						NewsResources newsResources = em.find(
								NewsResources.class, Integer
										.parseInt(ebookResource.getNewsrid()));
						em.remove(newsResources);
					}
					em.remove(ebookResource);
				}
			}
			return ebookSection;

	}

	@SuppressWarnings("unchecked")
	public Object get(Class clazz, Serializable id) {
		
		Object o = null;
		try {
			o = this.em.find(clazz, id);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		if (o == null) {
			String msg = "Uh oh, '" + clazz + "' object with id '" + id
					+ "' not found...";
			logger.warn(msg);
			throw new EntityNotFoundException(msg);
		}
	
		return o;
	}

	public static boolean StringIsNotNull(Object str) {
		boolean b = false;
		try {
			if (!str.equals("") && !str.equals("null")) {
				b = true;
			}
		} catch (Exception e) {
		}
		return b;
	}

	/**
	 * 内容章节排序
	 * 
	 * @return
	 */
	public boolean sortSection(String content_id, String gvalue) {
			
			String jpql = "";
			Query query = null;
			String[] gArys = gvalue.split("\\|");

			// 所有排序号清空
			jpql = "UPDATE TEbookSection t SET t.sectionorder=null WHERE t.tebookContent.contentid='"
					+ content_id + "'";
			query = em.createQuery(jpql);
			query.executeUpdate();
			int questorder = 1;
			for (int i = 0; i < gArys.length; i++) {
				// System.out.println("gArys[" + i + "]:" + gArys[i]);
				TEbookSection ebookSection = em.find(TEbookSection.class,
						Integer.parseInt(gArys[i]));
				ebookSection.setSectionorder(questorder);
				em.merge(ebookSection);
				em.flush();
				em.clear();
				questorder++;
			}

			// 排序过程中，防止有人操作内容章节
			jpql = "SELECT t FROM TEbookSection t WHERE  t.sectionorder is null AND t.tebookContent.contentid='"
					+ content_id + "'";
			query = em.createQuery(jpql);
			List<TEbookSection> ebookSectionList = query.getResultList();
			if (ebookSectionList.size() > 0) {
				for (TEbookSection ebookSection : ebookSectionList) {
					ebookSection.setSectionorder(questorder);
					questorder++;
				}
			}

		return true;
	}

	/**
	 * ajax 展示电子书内容对应栏目
	 * 
	 * @param contentid
	 * @return
	 */
	public List getChannelsbyEbookContentid(String contentid) {
		String sql = "select tc.channel_id,tc.channel_name from news_contenttitle nc,t_channels tc,news_extends_channel_title nect,news_extends_channel nec "
				+ "where nc.contentid='"
				+ contentid
				+ "' and nc.cid=nect.cid and nect.channleid=nec.channleid and tc.channel_id=nec.channel_id";
		try {
			return queryALLResultSet(sql);
		} catch (Exception e) {
			logger.info(" getChannelsbyPicture fail !!!" + e.getMessage());
			return null;
		}
	}

	/**
	 * 根据电子书类型得到类别list
	 * 
	 * @param key
	 * @return
	 */
	public List<TGenre> getGenreListByContent_type(String key) {
		
		String jpql = "SELECT t FROM TGenre t WHERE t.conentType='" + key
				+ "')";
		Query query = em.createQuery(jpql);
		List<TGenre> queryList= new ArrayList<TGenre>();
		try {
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return queryList;
	}

	/**
	 * findResourceBySection Html 内容
	 * 
	 * @param cid
	 * @return
	 */
	public ArrayList findResourceBySection(String sectionid) {
		String findSql = "SELECT ter.resourceid,ter.news_rid,ter.t_e_contentid,ter.sectionid,ter.useragent,ter.filename,ter.ctype,ter.spcode,ter.curl,ter.duration,ter.size,ter.cformat,ter.newformat,ter.fullpath" +
				" FROM t_ebook_resource ter,t_ebook_section tes where tes.sectionid="
				+ sectionid + " and tes.sectionid=ter.sectionid ";
		try {
			return queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.info(" findResourceByNews fail !!!" + e.getMessage());
			return null;
		}
	}

	/**
	 * getExistFilename Html 内容
	 * 
	 * @param cid
	 * @return
	 */
	public String getExistFilename(String sectionid) {
		String sql = "select ter.curl from t_ebook_resource ter, t_ebook_section tes where  ter.sectionid ='"
				+ sectionid
				+ "' and tes.sectionid=ter.sectionid and ter.cformat in ('mp3','3gp','mp4','aac')";
		try {
			return queryOne(sql);
		} catch (Exception e) {
			logger.info(" getExistFilename fail !!!" + e.getMessage());
			return null;
		}
	}

	/**
	 * getSpcodeByUserId Html 内容
	 * 
	 * @param userid
	 * @return
	 */
	public String getSpcodeByUserId(String userid) {
		String spcode = "";
		sql = "select te.sp_code from t_employee te, t_user tu where tu.employee_id=te.employee_id and tu.user_id='"
				+ userid + "'";
		try {
			spcode =this.getOneString();
		} catch (Exception e) {
			logger.info(" findNotChooseChannel fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return spcode;
	}


	/**
	 * addSectionResource Html 内容
	 * 
	 * @param newsResources
	 * @param news
	 */
	public void addSectionResource(TEbookResource ebookResource, News news) {
		ArrayList<String> sqlList = new ArrayList<String>();
	
		String sql = "";
		String resource_id = com.dp.util.BaseBean
				.ObjectToString(KeyGenerator.getInstance().getNextKeyValue(
						"t_resources"));
		if ("1".equals(ebookResource.getCtype())) {
			if ("1".equals(ebookResource.getCtype())) {
				// 图片增加一条记录到 news_resource表中
				sql = "insert into news_resources (name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values ('"
						+ ebookResource.getFilename()
						+ "',"
						+ ebookResource.getCtype()
						+ ",'"
						+ ebookResource.getCurl()
						+ "',"
						+ ebookResource.getSize()
						+ ",'"
						+ ebookResource.getCformat()
						+ "',"
						+ "'"
						+ ebookResource.getSpcode()
						+ "','"
						+ ebookResource.getNewformat()
						+ "','"
						+ ebookResource.getFullpath() + "')";
				sqlList.add(sql);
				System.out.println("sql1:" + sql);
			}

			sql = "insert into t_ebook_resource (resourceid,news_rid,t_e_contentid,sectionid,filename,ctype,cformat,spcode,curl,size,newformat,fullpath) values ('"
					+ resource_id
					+ "',(select LAST_INSERT_ID()),'"
					+ news.getContentId()
					+ "',"
					+ "'"
					+ news.getCId()
					+ "','"
					+ ebookResource.getFilename()
					+ "','"
					+ ebookResource.getCtype()
					+ "','"
					+ ebookResource.getCformat()
					+ "','"
					+ ebookResource.getSpcode()
					+ "'"
					+ ",'"
					+ ebookResource.getCurl()
					+ "','"
					+ ebookResource.getSize()
					+ "','"
					+ ebookResource.getNewformat()
					+ "','"
					+ ebookResource.getFullpath() + "')";
			System.out.println("sql2:" + sql);
		} else {
			sql = "insert into t_ebook_resource (resourceid,t_e_contentid,sectionid,filename,ctype,cformat,spcode,curl,size,newformat,fullpath) values ('"
					+ resource_id
					+ "','"
					+ news.getContentId()
					+ "',"
					+ "'"
					+ news.getCId()
					+ "','"
					+ ebookResource.getFilename()
					+ "','"
					+ ebookResource.getCtype()
					+ "','"
					+ ebookResource.getCformat()
					+ "','"
					+ ebookResource.getSpcode()
					+ "'"
					+ ",'"
					+ ebookResource.getCurl()
					+ "','"
					+ ebookResource.getSize()
					+ "','"
					+ ebookResource.getNewformat()
					+ "','"
					+ ebookResource.getFullpath() + "')";
			System.out.println("sql3:" + sql);
		}
		sqlList.add(sql);
		try {

			this.execTransaction(sqlList);
			logger.info("addNewsResource sql: " + sql);
		} catch (Exception e) {
			logger.info(" addNewsResource fail !!!" + e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 获得电子书内容资源列表 但不包括内容章节资源
	 * 
	 * @param contentid
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<TEbookResource> getTEbookResourceByContentid(String contentid) {
		String useragents = "";
		String UA_class_info = "";
		String useragentschar = "";
		
		List<TEbookResource> queryList = new ArrayList<TEbookResource>();
		try {
			
		String jpql = "SELECT t FROM TEbookResource t WHERE t.tebookContent.contentid='"
				+ contentid + "' AND t.tebookSection is null order by ctype desc";
		Query query = em.createQuery(jpql);
		queryList = query.getResultList();
		for (TEbookResource t : queryList) {
			useragents = t.getUseragent();
			if (useragents != null) {
				for (String u : useragents.split(",")) {
					if ("null".equals(u)) {
						continue;
					}
					if ("".equals(useragentschar)) {
						useragentschar = "'" + u + "'";
					} else {
						useragentschar += ",'" + u + "'";
					}
				}
				if (!"".equals(useragentschar)) {
					jpql = "SELECT uaClassInfo FROM TUaClass t WHERE 1=1 and uaClassId in ("
							+ useragentschar + ")";
					query = em.createQuery(jpql);
					List<String> queryList2 = query.getResultList();
					if (queryList2 != null && queryList2.size() > 0) {
						for (String s : queryList2) {
							if ("".equals(UA_class_info)) {
								UA_class_info = s;
							} else {
								UA_class_info += "," + s;
							}
						}
					}
					// System.out.println("UA_class_info:"+UA_class_info);
					t.setUseragent(UA_class_info);
				} else {
					t.setUseragent(null);
				}
			}
			
			if("1".equals(t.getCtype())){
				//页面展示240x320图片
				 File target = new File(t.getFullpath().substring(0,t.getFullpath().lastIndexOf("."))+"_240x320."+t.getNewformat());
				 if(target.exists()){
					 t.setFullpath(t.getFullpath().substring(0,t.getFullpath().lastIndexOf("."))+"_240x320."+t.getNewformat());
				 }
			}
			// 页面显示Fullpath
			t.setFullpath(t.getFullpath().replace(SysProperty.getPrep("uploadpath"), ""));
		}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		return queryList;
	}

	/**
	 * 增加电子书内容附件或封面图
	 * 
	 * @param ebookResource
	 * @return
	 */
	public boolean addEbookResource(List<TEbookResource> erlist) {
		boolean b = false;
			
			for(TEbookResource ebookResource:erlist){
				if ("1".equals(ebookResource.getCtype())) {

					String jpql = "SELECT t FROM TEbookResource t WHERE t.tebookContent.contentid='"
							+ ebookResource.getTebookContent().getContentid()
							+ "' AND t.tebookSection is null AND t.ctype='1'";
					Query query = em.createQuery(jpql);
					// System.out.println("jpql:"+jpql);
					Object obj = null;
					if (query.getResultList().size() > 0) {
						obj = query.getSingleResult();
					}

					TEbookResource ebookResource2 = null;
					if (obj != null) {
						ebookResource2 = (TEbookResource) obj;
						// 删除的记录插入t_resourcedelete
						TResourcedelete resourcedelete = new TResourcedelete();
						resourcedelete.setSpcode(ebookResource2.getSpcode());
						resourcedelete.setFormat(ebookResource2.getCformat());
						resourcedelete.setType(ebookResource2.getCtype());
						resourcedelete.setUrl(ebookResource2.getCurl());
						// 备用字段 not 备注
						// resourcedelete.setComments("ebook@resourceid:"+ebookResource.getResourceid()+",contentid:"+ebookResource.getTebookContent().getContentid()+",sectionid:"+ebookResource.getTebookSection().getSectionid()+"");
						em.persist(resourcedelete);

						// 删除原来的封面图 news_resource表中
						jpql = "DELETE FROM NewsResources  n WHERE n.rid='"
								+ ebookResource2.getNewsrid() + "' or n.name='"
								+ ebookResource2.getNewsrid() + "'";
						query = em.createQuery(jpql);
						obj = query.executeUpdate();
						// 删掉原来的封面图 t_ebook_resource表中 ctype=1
						em.remove(ebookResource2);
					}

					// 图片资源插入 news_resource
					NewsResources newsResources = new NewsResources();
					newsResources.setName(ebookResource.getFilename());
					try {
						newsResources.setResourcetype(Integer
								.parseInt(ebookResource.getCtype()));
					} catch (Exception e) {
						newsResources.setResourcetype(1);
					}
					newsResources.setUrl(ebookResource.getCurl());
					newsResources.setSize(ebookResource.getSize());
					newsResources.setRformat(ebookResource.getCformat());
					newsResources.setSpcode(ebookResource.getSpcode());
					newsResources.setNewformat(ebookResource.getNewformat());
					newsResources.setFullpath(ebookResource.getFullpath());

					newsResources = em.merge(newsResources);
					if (newsResources != null) {
						ebookResource.setNewsrid(newsResources.getRid().toString());
					} else {
						return false;
					}

				}
				em.persist(ebookResource);
			}
			b = true;
		return b;
	}

	public ArrayList getUaClass(String comid) {
        String sql = "SELECT t.UA_CLASS_ID,t.UA_CLASS, t.ua_class_info FROM t_ua_class t where com_id= " + comid;
        
        try {
            return queryALLResultSet(sql);
        } catch (Exception e) {
        	log.info(" getUaClass fail !!!" +e.getMessage());
            return null;
        }
    }
	 public boolean delUaclassByEbookResid(String resourceid,String uaclassid)
	    {
	    	 sql = "";
	    
	    	if(resourceid != null && !resourceid.equals(""))
	        	sql = "select useragent FROM t_ebook_resource where resourceid ='"+resourceid+"'";
	    	try {
		    	String useragents = this.getOneString();
		    	if(uaclassid != null)
		    	{
		    		String uaclassidstr = uaclassid + ",";
		    		String uaclsidstr = ","+uaclassid;
		    		if(useragents.contains(uaclassidstr))
		    			useragents = useragents.replace(uaclassidstr, "");
		    		else if(useragents.contains(uaclsidstr))
		    			useragents = useragents.replace(uaclsidstr, "");
		    		else if(useragents.contains(uaclassid))
		    			useragents = useragents.replace(uaclassid, "");
		    	}
		    	sql = "update t_ebook_resource set useragent='"+useragents+"' where resourceid='"+resourceid+"'";
		    	return execUpdate(sql);
	        } catch (Exception e) {
	        	log.info(" delUaclassByResid fail !!!" +e.getMessage());
	        	return false;
	        }
	        
	    }
	 
	/**
	 * ajax 删除电子书内容资源文件 上传附件 ebook-upload.jsp
	 * 
	 * @param resourceid
	 * @param content_id
	 * @return
	 */
	public boolean delEbookResourceById(String resourceid, String content_id) {
		ArrayList<String> sqlStrList = new ArrayList<String>();
		String sql1 = "";
		String sql2 = "";
		String sqlInsert = "";
		String deleteNews = "";
		try {
			if (resourceid != null && !resourceid.equals("")) {
				TEbookResource ebookResource = (TEbookResource) get(
						TEbookResource.class, resourceid);
				sqlInsert = "insert into t_resourcedelete (type,url,format) (select ter.ctype,ter.curl,ter.cformat from t_ebook_resource ter where ter.resourceid='"
						+ resourceid + "')";
				sqlStrList.add(sqlInsert);
				sql1 = "delete from t_ebook_resource where resourceid='"
						+ ebookResource.getResourceid() + "'";
				sqlStrList.add(sql1);
				if (ebookResource.getNewsrid() != null) {
					deleteNews = "delete from news_resources where rid='"
							+ ebookResource.getNewsrid() + "'";
					sqlStrList.add(deleteNews);
				}

			}
			boolean bool = execTransaction(sqlStrList);
			return bool;
		} catch (Exception e) {
			logger.info(" delResourceById fail !!!" + e.getMessage());
			return false;
		}
	}

	/**
	 * 根据电子书内容资源id 获得资源对象
	 * 
	 * @param resourceid
	 * @return TEbookResource
	 */
	public TEbookResource getTEbookResourceByResourceid(String resourceid) {
		
		TEbookResource ebookResource = new TEbookResource();
		String jpql = "SELECT t FROM TEbookResource t WHERE 1=1 AND t.resourceid='"
				+ resourceid + "'";
		
		Object obj = null;
		try {
			Query query = em.createQuery(jpql);
			obj = query.getSingleResult();
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		
		if (obj == null) {
			return null;
		} else {
			return (TEbookResource) obj;
		}
	}

	public ArrayList getMobileCompany(DataMap hashMap) {
		String sql = "SELECT t.com_id,t.com_name FROM t_mobile_company_info t where 1=1 ";
		try {
			return queryALLResultSet(sql);
		} catch (Exception e) {
			logger.info(" getMobileCompany fail !!!" + e.getMessage());
			return null;
		}
	}

	/**
	 * 获得当前ua组列表
	 * 
	 * @param resourceid
	 * @return
	 */
	public ArrayList getCurrentUaClassList_ebook(String resourceid) {
    	String sql = "";
//    	if(resourceid != null && !resourceid.equals(""))
//        	sql = "select * FROM t_ua_class where FIND_IN_SET(ua_class_id,( SELECT useragent FROM t_ebook_resource  where resourceid='"+resourceid+"')) >0 ";
        try {
        	return null;
//            return queryALLResultSet(sql);
        } catch (Exception e) {
        	log.info(" get current uaclass list fail !!!" +e.getMessage());
        	return null;
        }
    }

	/**
	 * 重设栏目
	 * 
	 * @param ebookContent
	 * @param channelid
	 * @return
	 */
	public TEbookContent resetConToChannel(TEbookContent ebookContent,
			String channelid) {
		boolean b = false;

			// 更新电子书内容 栏目-内容(NewsContenttitle) 栏目-电子书内容关系(TChannelEbook)
			String jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
					+ ebookContent.getContentid() + "'";
			Query query = em.createQuery(jpql);
			Integer cid = Integer.parseInt(query.getSingleResult().toString());
			// 删除电子书内容 原 栏目-内容
			jpql = "DELETE FROM NewsExtendsChannelTitle WHERE newsExtendsChannelTitlePK.cid="
					+ cid + "";
			query = em.createQuery(jpql);
			query.executeUpdate();
			// 删除电子书内容 原 栏目-电子书内容关系
			jpql = "DELETE FROM TChannelEbook WHERE channelEbookPK.contentid="
					+ cid + "";
			query = em.createQuery(jpql);
			query.executeUpdate();

			// if(channelid!=null&&!"".equals(channelid)){
			// 增加电子书内容 栏目-内容
			for (String chid : channelid.split(",")) {
				// 频道栏目关联中间表 取自增长channleid
				jpql = "select channleid from NewsExtendsChannel where channelId='"
						+ chid + "'";
				query = em.createQuery(jpql);
				Integer channleid = Integer.parseInt(query.getSingleResult()
						.toString());

				NewsExtendsChannelTitle newsExtendsChannelTitle = new NewsExtendsChannelTitle();
				newsExtendsChannelTitle
						.setNewsExtendsChannelTitlePK(new NewsExtendsChannelTitlePK(
								channleid, cid));
				newsExtendsChannelTitle.setContentstatus(0);
				newsExtendsChannelTitle.setIstest(1);
				newsExtendsChannelTitle.setIsnew(1);
				em.persist(newsExtendsChannelTitle);

				// 栏目-电子书内容关联中间表
				TChannelEbook channelEbook = new TChannelEbook();
				channelEbook.setChannelEbookPK(new ChannelEbookPK(cid,
						channleid));
				em.persist(channelEbook);
			}
			return ebookContent;
	}

	/**
	 * 更新电子书内容状态 提交审核
	 * 
	 * @param strIdList
	 * @param status
	 * @return
	 */
	public boolean updateEbookStatus(String strIdList, String status) {
		try {
			
			// 更新电子书内容状态
			String jpql = "UPDATE TEbookContent SET status='" + status
					+ "' WHERE contentid in (" + strIdList + ")";
			Query query = em.createQuery(jpql);
			Object obj = query.executeUpdate();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 电子书类别
	 * 
	 * @param type
	 * @return
	 */
	public List<TGenre> findTGenrebyType(String type) {
		
		StringBuffer sf = new StringBuffer("SELECT t FROM TGenre t WHERE 1=1");
		if (type != null && type.toString().trim().length() > 0) {
			sf.append(" AND t.conentType='" + type + "'");
		}
		List<TGenre> queryList=new ArrayList<TGenre>();
		try {
			Query query = em.createQuery(sf.toString());
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return queryList;
	}

	/**
	 * 电子书内容审核
	 * 
	 * @param Cause
	 * @param strIdList
	 * @return
	 */
	public boolean auditEbooks(DataMap hashMap) {
		String user_id = (String) hashMap.get("user_id");
		String Cause = (String) hashMap.get("Cause");
		String strIdList = (String)hashMap.get("strIdList");
		if (Cause == null) {
			for (String contentid : strIdList.split(",")) {
				// 转换图片
				String resourceid=null;
				try {
					resourceid = scaleImage(contentid);
				} catch (Exception e) {
					logger.info(" parse content icon fail !!!" + e.getMessage());
					e.printStackTrace();
				}
				if (resourceid == null) {
					return false;
				}
				
				// 更新电子书内容状态 pass
				String jpql = "UPDATE TEbookContent SET status='pass',audituser='"+user_id+"',cause=null WHERE contentid='"
						+ contentid + "'";
				Query query = em.createQuery(jpql);
				Object obj = query.executeUpdate();
				
				// 更新 news_contenttitle.contenticon
				String contenticon = SysProperty.getPrep("sysiconid_title");
				if (contenticon == null || contenticon.equals(""))
					contenticon = "1";
				
				if("".equals(resourceid)){
					//没有图片
					jpql = "update NewsContenttitle set contenticon='"+contenticon+"' where contentid='"
						+ contentid
						+ "'";
				}else{
					jpql = "update NewsContenttitle set contenticon=(select max(rid) from NewsResources where name='"
						+ resourceid
						+ "') where contentid='"
						+ contentid
						+ "'";
				}
				
				query = em.createQuery(jpql);
				query.executeUpdate();
				TEbookContent ebookContent = new TEbookContent();
				ebookContent = em.find(TEbookContent.class, contentid);
				jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
						+ ebookContent.getContentid() + "'";
				query = em.createQuery(jpql);
				Integer cid = Integer.parseInt(query.getSingleResult()
						.toString());
				// 更新主题内容关联栏目 contentstatus=2
				jpql = "UPDATE NewsExtendsChannelTitle SET contentstatus=2 WHERE newsExtendsChannelTitlePK.cid="
						+ cid + "";
				query = em.createQuery(jpql);
				obj = query.executeUpdate();
			}

		} else {
			String charIdList = "";
			for (String str : strIdList.split(",")) {
				charIdList = charIdList + "'" + str + "',";
			}
			if (!charIdList.equals("")) {
				charIdList = charIdList.substring(0,
						charIdList.length() - 1);
			}
			// 更新主题内容状态 nopass
			String jpql = "UPDATE TEbookContent SET status='unpass',audituser='"+user_id+"',cause='"
					+ Cause + "' WHERE contentid in (" + charIdList + ")";
			Query query = em.createQuery(jpql);
			Object obj = query.executeUpdate();
		}
		
		return true;
	}

	/**
	 * 电子书内容审核通过后转换图片到 news_resources
	 * 
	 * @param contentid
	 * @param db
	 * @return
	 */
	public String scaleImage(String contentid) throws Exception{
		String jpql = "SELECT t FROM TEbookResource t WHERE ctype='1'  AND t.tebookSection is null AND t.tebookContent.contentid='"
				+ contentid + "'";
		List<TEbookResource> terList = null;
		String resourceid = "";
		    Query query = em.createQuery(jpql);
			terList = query.getResultList();
			if (terList.size() > 0) {
				// 转换一张icon
				TEbookResource ebookResource = terList.get(0);
				resourceid = ebookResource.getNewsrid();
				String fullpath = ebookResource.getFullpath();
				ImageScalee ims = new ImageScalee();
				String imageSizeScaleStr = SysProperty
						.getPrep("news_imagesizescale");
				String imageFormatScaleStr = SysProperty
						.getPrep("news_imageformatscale");
				if (imageFormatScaleStr == null
						|| imageFormatScaleStr.equals(""))
					imageFormatScaleStr = "png";
				String[] imageSizeScaleAry = imageSizeScaleStr.split(",");
				String[] imageFormatScaleAry = imageFormatScaleStr.split(",");
				if (imageSizeScaleAry != null && imageSizeScaleAry.length > 0) {
					for (String imageSizeScale : imageSizeScaleAry) {
						String screenWidHei = imageSizeScale.split("@")[0];
						String picWidHei = imageSizeScale.split("@")[1];
						int screenWidth = Integer.parseInt(screenWidHei
								.split("x")[0]);
						int screenHeight = Integer.parseInt(screenWidHei
								.split("x")[1]);
						int width = Integer.parseInt(picWidHei.split("x")[0]);
						int height = Integer.parseInt(picWidHei.split("x")[1]);
						if (imageFormatScaleAry != null
								&& imageFormatScaleAry.length > 0)
							for (String imageFormatScale : imageFormatScaleAry) {
								try {
									ims.compressPicsScale(fullpath, width,
											height, imageFormatScale,
											screenWidth, screenHeight);
								} catch (Exception e) {
									logger.error(e.getMessage());
									return null;
								}
							}

					}
				}

				// 如果存在 删除原图标 （之前上线过 再修改 再提交审核）
				jpql = "DELETE FROM NewsResources WHERE name='" + resourceid
						+ "'";
				query = em.createQuery(jpql);
				query.executeUpdate();

				String scaleFullPath = fullpath.replace(".", "-p.");
				NewsResources newsResources = new NewsResources();
				newsResources.setName(resourceid);
				newsResources.setNewformat(imageFormatScaleStr);
				newsResources.setFullpath(scaleFullPath);
				em.merge(newsResources);
			}
		return resourceid;
	}

	/**
	 * 电子书内容下线
	 * 
	 * @param tsubject
	 * @return
	 */
	public boolean disableContent(TEbookContent ebookContent) {
			
			// 修改电子书内容状态为 disable
			ebookContent.setStatus("disable");
			ebookContent.setAudituser(null);
			em.merge(ebookContent);

			String jpql = "SELECT cid FROM NewsContenttitle WHERE contentid='"
					+ ebookContent.getContentid() + "'";
			Query query = em.createQuery(jpql);
			Integer cid = Integer.parseInt(query.getSingleResult().toString());
			// 更新电子书内容关联栏目下 内容状态 contentstatus=3
			jpql = "UPDATE NewsExtendsChannelTitle SET contentstatus=3 WHERE newsExtendsChannelTitlePK.cid="
					+ cid + "";
			query = em.createQuery(jpql);
			Object obj = query.executeUpdate();

		
		return true;
	}

	/**
	 * 电子书内容章节下线
	 * 
	 * @param tsubject
	 * @return
	 */
	public boolean disableSection(TEbookSection ebookSection) {
		try {
			
			// 修改电子书内容状态为 disable
			ebookSection.setSectionstatus("disable");
			ebookSection.setAuditer(null);
			em.merge(ebookSection);

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 获得内容章节资源总大小
	 * 
	 * @param sectionid
	 * @return
	 */
	public int getResSizeBySectionid(Integer sectionid) {
		 sql = "SELECT sum(size) FROM t_ebook_resource ter "
				+ "where ter.sectionid=" + sectionid + "";
		try {
			logger.info(" getResSize excute sql:" + sql);
			
			return this.getOneInt() / 1024;
		} catch (Exception e) {
			logger.info(" getResSize fail !!!" + e.getMessage());
			e.printStackTrace();
			return 0;
		}
	}

	/**
	 * 电子书内容章节 审核
	 * 
	 * @param Cause
	 * @param strIdList
	 * @return
	 */
	public boolean auditSections(DataMap hashMap) {
		String user_id = (String) hashMap.get("user_id");
		String Cause = (String) hashMap.get("Cause");
		String strIdList = (String)hashMap.get("strIdList");
			
			if (Cause == null) {
				for (String sectionid : strIdList.split(",")) {
					// 更新电子书内容章节状态 pass
					String jpql = "UPDATE TEbookSection SET sectionstatus='pass',auditer='"+user_id+"',cause=null WHERE sectionid="
							+ sectionid + "";
					Query query = em.createQuery(jpql);
					Object obj = query.executeUpdate();

					jpql = "SELECT t FROM TEbookResource t WHERE t.tebookSection.sectionid="
					+ sectionid + "";
					query = em.createQuery(jpql);
					List<TEbookResource> queryList=query.getResultList();
					
					for(TEbookResource t:queryList){
						ImageScalee ims = new ImageScalee();
						String imageSizeStr = SysProperty.getPrep("ebook_imagesize");
						String[] imageSizeArys = null;
						int[] imageSizeAry = new int[4];
						if (imageSizeStr != null && !imageSizeStr.equals("")) {
							imageSizeArys = SysProperty.getPrep("ebook_imagesize")
									.split(",");
						}
						String imageFormat = SysProperty.getPrep("ebook_imageformat");
						if (imageFormat == null || imageFormat.equals(""))
							imageFormat = "jpg";

						for (String imageSize : imageSizeArys) {
							for (int k = 0; k < imageSize.split("x|@").length; k++) {
								imageSizeAry[k] = Integer.parseInt(imageSize
										.split("x|@")[k]);
							}
							try {
								ims.compressPics(t.getFullpath(),
										imageSizeAry[2], imageSizeAry[3],
										imageFormat, imageSizeAry[0],
										imageSizeAry[1]);
							} catch (IOException e) {
								e.printStackTrace();
							}
						}
						
					}
					
					
				}

			} else {
				String charIdList = "";
				for (String str : strIdList.split(",")) {
					charIdList = charIdList + "'" + str + "',";
				}
				if (!charIdList.equals("")) {
					charIdList = charIdList.substring(0,
							charIdList.length() - 1);
				}
				// 更新主题内容状态 nopass
				String jpql = "UPDATE TEbookSection SET sectionstatus='unpass',auditer='"+user_id+"',cause='"
						+ Cause + "' WHERE sectionid in (" + charIdList + ")";
				Query query = em.createQuery(jpql);
				Object obj = query.executeUpdate();
			}
		
		return true;
	}

	/**
	 * 更新电子书内容状态 提交审核
	 * 
	 * @param strIdList
	 * @param status
	 * @return
	 */
	public boolean updateEbook_SectionStatus(String strIdList, String status) {
		try {
			
			// 更新电子书内容章节状态
			String jpql = "UPDATE TEbookSection SET sectionstatus='" + status
					+ "' WHERE sectionid in (" + strIdList + ")";
			Query query = em.createQuery(jpql);
			Object obj = query.executeUpdate();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 待审核内容章节所属内容列表
	 * 
	 * @param maxrow
	 * @param firstrow
	 * @param dataMap
	 * @param ebookContent
	 * @param maxrow
	 * @param firstrow
	 * @return
	 */
	public List<TEbookContent> getTEbookContentListByAuditingSection(
			DataMap dataMap, Integer firstrow, Integer maxrow) {
		
		TEbookContent ebookContent = null;
		if (dataMap.get("ebookContent") != null) {
			ebookContent = (TEbookContent) dataMap.get("ebookContent");
		}
		List<TEbookContent> queryList = null;
		try {
			StringBuffer sf = new StringBuffer(
					"SELECT distinct tec FROM TEbookContent tec,TEbookSection tes");

			String channelid = "";
			// 按栏目查询
			if (dataMap.get("channelid") != null) {
				channelid = dataMap.get("channelid").toString();
				sf
						.append(" ,NewsContenttitle nc,NewsExtendsChannelTitle nect,NewsExtendsChannel nec ");
				sf
						.append(" WHERE nc.cid=nect.newsContenttitle.cid  and tec.contentid=nc.contentid and nect.newsExtendsChannelTitlePK.channleid=nec.channleid  and nec.channelId.channelId='"
								+ channelid + "'");
			}
			if (sf.toString().indexOf("WHERE") == -1) {
				sf
						.append(" WHERE tes.tebookContent.contentid=tec.contentid AND tec.status='pass' AND tes.sectionstatus='auditing' ");
			} else {
				sf
						.append(" AND tes.tebookContent.contentid=tec.contentid AND tec.status='pass' AND tes.sectionstatus='auditing' ");
			}
			if (ebookContent != null) {
				if (ebookContent.getContentid() != null
						&& ebookContent.getContentid().toString().trim()
								.length() > 0) {
					sf.append(" AND tec.contentid='"
							+ ebookContent.getContentid() + "'");
				}

				if (ebookContent.getBookname() != null
						&& ebookContent.getBookname().toString().trim()
								.length() > 0) {
					sf.append(" AND tec.bookname like '%"
							+ ebookContent.getBookname() + "%'");
				}
			}

			sf.append(" order by tec.lastupdatetime desc,tec.contentid desc");
			Query query = em.createQuery(sf.toString());
			if (firstrow != null) {
				query.setFirstResult(firstrow);
			}
			if (maxrow != null) {
				query.setMaxResults(maxrow);
			}
			queryList = query.getResultList();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return queryList;
	}

	/**
	 *  验证电子书唯一编码
	 * @param urlB
	 * @return
	 */
	public int checkMarkcode(String markcode,String contentid) {
		int iCode=0;
		try {
			
			StringBuffer sf = new StringBuffer("SELECT t FROM TEbookContent t WHERE t.markcode=:markcode and t.contentid!=:contentid");
			Query query = em.createQuery(sf.toString());
			query.setParameter("markcode", markcode);
			query.setParameter("contentid", contentid);
			if(query.getResultList().size()>0){
				iCode=1;
			}
		} catch (Exception e) {
			logger.warn(e.getMessage());
		}
		return iCode;
	}
	
	/**
	 * 删除漫画 图片
	 * 
	 * @param sectionid
	 * @return
	 */
	public int delComic_pic(Integer sectionid) {
		int iCode = 1;
			
			String jpql = "delete from NewsResources where rid=(select newsrid  from  TEbookResource where fullpath=(select filepath from TEbookSection tbs where tbs.sectionid="+sectionid+"))";
			Query query = em.createQuery(jpql);
			query.executeUpdate();
			
			jpql = "delete from  TEbookResource where fullpath=(select filepath from TEbookSection tbs where tbs.sectionid="+sectionid+")";
		    query = em.createQuery(jpql);
			query.executeUpdate();
			
			jpql = "UPDATE TEbookSection SET filepath=null,islink=1  where sectionid="+sectionid;
		    query = em.createQuery(jpql);
			query.executeUpdate();
		
		return iCode;
	}
	
	/**
	 * 用户可支配的栏目
	 * @param hashMap
	 * @return
	 */
	public ArrayList<DataMap> findAllLastChannel(Object roleId, String userId,String userids) {
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +" from t_channels ch WHERE 1=1 " +
				//will open
				//" and status='"+BookConfig.channel_status_enable+"'" +
				" and (channel_type='"+BookConfig.channel_type_ebook+"' or ch.channel_type='"+BookConfig.channel_type_magazine+"') " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
		    		//" and status='"+BookConfig.channel_status_enable+"'" +
		    		" and (channel_type='"+BookConfig.channel_type_ebook+"' or ch.channel_type='"+BookConfig.channel_type_magazine+"') " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			findSql = "select distinct  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
	    		//" and status='"+BookConfig.channel_status_enable+"'" +
	    		" and (channel_type='"+BookConfig.channel_type_ebook+"' or ch.channel_type='"+BookConfig.channel_type_magazine+"') " + 
	    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
	    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	 public DataMap getEbook_Resource(String  resourceid) {

    	String sql = "select resourceid,news_rid,t_e_contentid,sectionid,useragent,filename,ctype,spcode,curl,duration,size,cformat,newformat,fullpath" +
    			" from t_ebook_resource where resourceid= '" + resourceid + "'";
        try {
            return null;
        } catch (Exception e) {
        	log.info(" getResource fail !!!" +e.getMessage());
            return null;
        }
    } 
	 public String getCurrentUaClass_ebook(String resourceid) {
    	String sql = "";
    	if(resourceid != null && !resourceid.equals(""))
        	sql = "SELECT useragent FROM t_ebook_resource t where resourceid='" + resourceid + "'";
        try {
            return queryOne(sql);
        } catch (Exception e) {
        	log.info(" get current uaclass id fail !!!" +e.getMessage());
        	return "";
        }
    }
	 
	 public boolean updateEbookResourceUa(String useragent,String resourceid) {
        String sql = "update t_ebook_resource set useragent='"+useragent+"' where resourceid='" + resourceid + "'";
        try {
            return execUpdate(sql);
        } catch (Exception e) {
        	log.info(" updateResourceUa fail !!!" +e.getMessage());
        	return false;
        }
    }
	 
	 //add 1119 select channel update
    public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
			chList = queryALLResultSet(sql);
		} catch (Exception e) {
			log.info(" java bean buildChChildIdAndPreviousIdMap fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
    
    private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null) && !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }

    
    /*==============================================================*/
	/* Wo杂志制作Start                                         
	/*==============================================================*/
    /**
     * 根据电子书内容id返回内容类型
     * @param contentid
     * @return newstype
     * @throws Exception
     */
	public String getEbookTypeByContentid(String contentid) throws Exception {
		sql="select nct.newstype from t_ebook_content tec,news_contenttitle nct where tec.contentid=nct.contentid and tec.contentid='"+contentid+"'";
		String newstype = getOneString();
		return newstype;
	}
	
	public List<NewsResources> getHeaderpicture() {
		String hql = "SELECT a FROM NewsResources a where 1=1 and resourcetype=13";
		return getQueryList(hql);
	}
	
	/**
	 *  验证杂志内容章节名称唯一
	 * @param city,city_old
	 * @return
	 */
	public int checkSectionname_unique(String contentid,String sectionname,String sectionname_old,int mtype) {
		int resultInt = 0;
		try {
			//this.init();
			this.sql="SELECT count(*) FROM t_ebook_section WHERE t_e_contentid='"+contentid+"'" +
					" AND sectionname='"+sectionname+"' AND sectionname!='"+sectionname_old+"' AND isfree='"+mtype+"' ";
			
			if(this.getOneInt()>0){
				if(sectionname_old!=null){
					if(!sectionname_old.equals(sectionname)){
						return 1;
					}else{
						return 0;
					}
				}
				return 1;
			}
		
		} catch (Exception e) {
			resultInt=-1;
			logger.info("checkSectionname_unique fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return resultInt;
	}
	
	/**
	 * 删除电子杂志内容章节
	 * @param content_id
	 * @param section_id
	 * @return
	 */
	public boolean deleteSectionContent(String content_id,String section_id) {
		sql="delete from t_ebook_section where t_e_contentid=? and sectionid=?";
		Query query=em.createNativeQuery(sql);
		query.setParameter(1, content_id);
		query.setParameter(2, section_id);
		query.executeUpdate();
		return true;
	}
	/*============================================================*/
	/* Wo杂志制作End                                         
	/*==============================================================*/

	public boolean autoSectionorder(String content_id, Integer isfree) {
		String jpql = "SELECT t FROM TEbookSection t WHERE  t.tebookContent.contentid=? AND t.isfree=? AND sectionorder>0 order by sectionorder desc";
		Query query = em.createQuery(jpql);
		query.setParameter(1, content_id);
		query.setParameter(2, isfree);
		List<TEbookSection> ebookSectionList = query.getResultList();
		int questorder=ebookSectionList.size();
		if (ebookSectionList.size() > 0) {
			for (TEbookSection ebookSection : ebookSectionList) {
				ebookSection.setSectionorder(questorder);
				questorder--;
			}
		}
		return true;
	}
   
}
